const prompts = require('prompts');
const fs = require('fs-extra');
const path = require('path');

const CITY_LIST = Object.keys(require('../json/city.json'));
const AREA_OBJECT = require('../json/area.json');
const HOUSE_TYPE = require('../constant/index.js');
const HOUSE_TYPE_LIST = Object.values(HOUSE_TYPE);

const workspace = process.cwd();

class Window {
	constructor() {
		this.name = 'window';
		this.handleCancel = async () => {
			throw new Error('exit');
		};
	}

	async open() {
		let cookie = '';

		const q1 = await prompts({
			type: 'select',
			name: 'house_type',
			message: '请选择要查询的数据类型:',
			choices: HOUSE_TYPE_LIST.map(item => {
				return {
					title: item,
					value: item
				}
			})
		}, {
			onCancel: this.handleCancel
		});

		if (q1.house_type === HOUSE_TYPE.ER_SHOU_FANG_CHENG_JIAO) {
			const _qq1 = await prompts({
				type: 'text',
				name: 'cookie',
				message: '请输入贝壳找房cookie.txt存放的绝对路径:',
			}, {
				onCancel: this.handleCancel
			});

			cookie = path.normalize(_qq1.cookie);
		}

		const q2 = await prompts({
			type: 'select',
			name: 'city',
			message: '请选择要查找的城市名称',
			choices: [
				...CITY_LIST.map(data => {
					return {
						title: data,
						value: data
					}
				})
			]
		}, {
			onCancel: this.handleCancel
		});

		const q3 = await prompts({
			type: 'select',
			name: 'area',
			message: '请选择要查找的区域名称',
			choices: [
				{
					title: '全部',
					value: ''
				},
				...Object.values(AREA_OBJECT[q2.city])
					.map((item) => {
						return Object.keys(item)[0];
					})
					.map(item => {
						return {
							title: item,
							value: item
						}
					})
			]
		}, {
			onCancel: this.handleCancel
		});

		const q4 = await prompts({
			type: 'number',
			name: 'page',
			message: '请输入要查找的页数(1-100)',
			validate: (value) => {
				const flag = typeof value === 'number' && (value > 0 && value <= 100);

				if (flag) {
					return flag;
				} else {
					return '请输入一个0-100的数字';
				}
			}
		}, {
			onCancel: this.handleCancel
		});

		return {
			type: q1.house_type,
			city: q2.city,
			area: q3.area,
			page: q4.page,
			cookie
		};
	}
}

module.exports = Window;